Repository navigation
fix(drivers): read every Snowflake private-key format - #1777
Conversation
Normalize pasted PEMs (quotes, literal \n, space-separated bodies, CRLF) and convert unencrypted PKCS#1/PKCS#8, encrypted PKCS#8 and legacy-encrypted PKCS#1 keys to PKCS#8. A missing or wrong passphrase now gives an actionable error without key material. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 13 minutes. View limit details
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
|
This PR doesn't fully meet our contributing guidelines and PR template. What needs to be fixed:
Please edit this PR description to address the above within 2 hours, or it will be automatically closed. If you believe this was flagged incorrectly, please let a maintainer know. |
|
Thanks for your contribution! This PR doesn't have a linked issue. All PRs must reference an existing issue. Please:
See CONTRIBUTING.md for details. |
|
|
||
| import * as crypto from "crypto" | ||
|
|
||
| const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+?)-----([\s\S]*?)-----END \1-----/ |
There was a problem hiding this comment.
WARNING: PEM_BLOCK takes the first BEGIN/END block in the text regardless of its label, and toPkcs8Pem then rejects it if the label is not a private-key label. A multi-block PEM file where a non-key block comes first (e.g. a certificate chain followed by the private key, or a public key above the private key) is therefore reported as format is not recognized and the connection fails.
That input previously worked: connect() passed unencrypted key text through verbatim and OpenSSL's PEM reader skips non-matching blocks until it finds the private key. Matching a private-key label explicitly keeps that behavior while still rejecting public-only PEMs (the not recognized path).
| const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+?)-----([\s\S]*?)-----END \1-----/ | |
| const PEM_BLOCK = /-----BEGIN ((?:ENCRYPTED |RSA |EC )?PRIVATE KEY)-----([\s\S]*?)-----END \1-----/ |
There was a problem hiding this comment.
Fixed in 61c7e51: the parser now scans every PEM block and uses the first private-key block, with tests for a public key placed before plain and encrypted private keys.
Code Review SummaryStatus: No Issues Found | Recommendation: Merge Incremental review of Files Reviewed (2 files)
Previous Review Summaries (3 snapshots, latest commit ea3d60b)Current summary above is authoritative. Previous snapshots are kept for context only. Previous review (commit ea3d60b)Status: 1 Issue Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
The prior WARNING (non-key block before the private key) and the prior SUGGESTION (unreachable fallback) are both fixed at this HEAD. Fix these issues in Kilo Cloud Previous review (commit 61c7e51)Status: 1 Issue Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Previous review's WARNING (multi-block PEM where a non-key block precedes the private key) is fixed: the parser now scans all blocks, selects the first private-key label, and the new test covers a public key placed before plain and encrypted private keys. Fix these issues in Kilo Cloud Previous review (commit bdb87a8)Status: 1 Issue Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
Files Reviewed (3 files)
Reviewed by deepseek-v4.1-flash-1017 · Input: 0 · Output: 0 · Cached: 0 Review guidance: REVIEW.md from base branch |
|
review-loop: APPROVED at bdb87a8 (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
||
| // A pasted file may hold other blocks (certificates, public key) before the | ||
| // private key; use the first block that is a private key. | ||
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source)) |
There was a problem hiding this comment.
SUGGESTION: Redundant fallback can be dropped
find returns undefined only when no block's label ends in PRIVATE KEY, so ?? text.match(new RegExp(PEM_BLOCK.source)) re-reads the first block, which toPkcs8Pem then rejects with the same not recognized error through its label check. The fallback therefore never changes observable behavior; it only recompiles the regex on every call and contradicts the comment above it ("use the first block that is a private key").
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source)) | |
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) |
There was a problem hiding this comment.
Fixed in ea3d60b: the fallback is removed.
There was a problem hiding this comment.
1 issue found across 3 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/drivers/src/snowflake-key.ts">
<violation number="1" location="packages/drivers/src/snowflake-key.ts:95">
P2: `toPkcs8Pem` accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach `SNOWFLAKE_JWT` and fail later in the SDK; validate `asymmetricKeyType` and `modulusLength` before exporting.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| try { | ||
| const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) | ||
| return keyObject.export({ type: "pkcs8", format: "pem" }).toString() | ||
| } catch { | ||
| if (encrypted) { | ||
| throw new Error( | ||
| "Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " + | ||
| "or the key is corrupted or uses an unsupported cipher.", | ||
| ) | ||
| } | ||
| throw new Error( | ||
| "Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " + | ||
| "use an RSA key in PKCS#8 or PKCS#1 PEM form.", | ||
| ) | ||
| } |
There was a problem hiding this comment.
P2: toPkcs8Pem accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach SNOWFLAKE_JWT and fail later in the SDK; validate asymmetricKeyType and modulusLength before exporting.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/drivers/src/snowflake-key.ts, line 95:
<comment>`toPkcs8Pem` accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach `SNOWFLAKE_JWT` and fail later in the SDK; validate `asymmetricKeyType` and `modulusLength` before exporting.</comment>
<file context>
@@ -0,0 +1,110 @@
+ )
+ }
+
+ try {
+ const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
+ return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
</file context>
| try { | |
| const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) | |
| return keyObject.export({ type: "pkcs8", format: "pem" }).toString() | |
| } catch { | |
| if (encrypted) { | |
| throw new Error( | |
| "Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " + | |
| "or the key is corrupted or uses an unsupported cipher.", | |
| ) | |
| } | |
| throw new Error( | |
| "Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " + | |
| "use an RSA key in PKCS#8 or PKCS#1 PEM form.", | |
| ) | |
| } | |
| let keyObject: crypto.KeyObject | |
| try { | |
| keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) | |
| } catch { | |
| if (encrypted) { | |
| throw new Error( | |
| "Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " + | |
| "or the key is corrupted or uses an unsupported cipher.", | |
| ) | |
| } | |
| throw new Error( | |
| "Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " + | |
| "use an RSA key in PKCS#8 or PKCS#1 PEM form.", | |
| ) | |
| } | |
| const modulusLength = keyObject.asymmetricKeyDetails?.modulusLength ?? 0 | |
| if (keyObject.asymmetricKeyType !== "rsa" || modulusLength < 2048) { | |
| throw new Error("Snowflake private key must be an RSA key with at least 2048 bits.") | |
| } | |
| return keyObject.export({ type: "pkcs8", format: "pem" }).toString() |
There was a problem hiding this comment.
Not changing this here: the issue is about reading pasted formats, and rejecting other key types or sizes could break keys that work today. The SDK and Snowflake already report an unsupported key type or size when connecting.
|
review-loop: APPROVED at 61c7e51 (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| } | ||
| expect(msg).toMatch(/passphrase .* incorrect/) | ||
| expect(msg).not.toMatch(/DECODER|bad decrypt|wrong/) | ||
| for (const line of pem.split("\n").filter((l) => /^[A-Za-z0-9+/=]{40,}$/.test(l))) { |
There was a problem hiding this comment.
SUGGESTION: Guard the redaction assertion against an empty match set
This loop only proves anything when the filter matches at least one body line. If the PEM layout ever changes (a shorter final line, an unwrapped body, a cipher with different line lengths), the filtered list is empty and the test passes without checking anything, silently losing the leak protection this test exists for.
Collect the lines first and assert the set is non-empty before looping, e.g. const lines = pem.split("\n").filter(...) then expect(lines.length).toBeGreaterThan(0) before for (const line of lines) expect(msg).not.toContain(line).
There was a problem hiding this comment.
Fixed in 7c5c792: the test asserts that ciphertext body lines were found before checking them.
|
review-loop: APPROVED at ea3d60b (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
dev-punia-altimate
left a comment
There was a problem hiding this comment.
🤖 Code Review — OpenCodeReview (Gemini) — 1 finding(s)
- 1 anchored to a line (posted inline when the comment stream is on)
- 0 without a line anchor
All findings (full text)
1. packages/drivers/src/snowflake-key.ts (L41)
[🟠 MEDIUM] Since matchAll already finds all matches in the text, you can avoid re-instantiating a new RegExp and re-scanning the string by reusing the matches array. This is more efficient and cleaner.
Suggested change:
const matches = [...text.matchAll(PEM_BLOCK)]
const match = matches.find((m) => /PRIVATE KEY$/.test(m[1])) ?? matches[0]
|
|
||
| // A pasted file may hold other blocks (certificates, public key) before the | ||
| // private key; use the first block that is a private key. | ||
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source)) |
There was a problem hiding this comment.
[🟠 MEDIUM] Since matchAll already finds all matches in the text, you can avoid re-instantiating a new RegExp and re-scanning the string by reusing the matches array. This is more efficient and cleaner.
Suggested change:
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source)) | |
| const matches = [...text.matchAll(PEM_BLOCK)] | |
| const match = matches.find((m) => /PRIVATE KEY$/.test(m[1])) ?? matches[0] |
There was a problem hiding this comment.
Already addressed in ea3d60b: the fallback was removed, so the regex is no longer re-instantiated.
🤖 Code Review — OpenCodeReview (Gemini) — 1 finding(s)
All findings (full text)1.
|
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
review-loop: APPROVED at 7c5c792 (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
sahrizvi
left a comment
There was a problem hiding this comment.
Consensus review: APPROVE. Panel: Claude (lead) and Codex (independent pass, then a second round on each other's findings). The OpenRouter models were not used for this review.
What was checked. No live Snowflake key-pair login was made. There was no Snowflake account for this review. All keys were generated at review time with node:crypto and openssl 3.6. connect() was driven at the merge base and at the head with a fake snowflake-sdk, under Bun (the CLI's runtime). The key handed to the SDK was then checked in three ways: it passes the SDK's own isPrivateKey shape check (snowflake-sdk 2.x), it loads with crypto.createPrivateKey, and its public key matches the input key's public key.
- Formats and variants: 15 key formats × 18 variants = 270 inputs. No input that loaded at the base fails at the head. No output has a different public key from its input. 117 inputs that failed at the base now load, including PKCS#1 without a passphrase, which the SDK rejected on main.
- Regression set: multiline PKCS#8,
\n-escaped PKCS#8, and encrypted PKCS#8 with the passphrase all give the same key at base and head. - Error messages: the key text, the passphrase, the normalized PEM and the OpenSSL text are never thrown, logged or returned by the new code. The decrypted key stays in memory and is passed only as
privateKeywithauthenticator: "SNOWFLAKE_JWT". Nothing is written to disk. - Removed lines in
snowflake.ts: they did only three things: replace literal\n, decrypt when a passphrase orENCRYPTEDwas present, and pass the key through unchanged otherwise. Nothing else was dropped. Password, OAuth, externalbrowser andprivate_key_pathbehave the same as before. Aprivate_key_pathfile now goes through the same normalizer, which also fixes space-joined key files. - Tests:
packages/drivers/testpasses at head (755 pass, 3 skip, 0 fail) and at base (719 pass, 0 fail). The newconnect()tests fail 5 of 36 against the base driver, as the PR says. - Typecheck:
bun run typecheck --forcepasses, andtsc --noEmitonpackages/drivershas 0 errors. - Marker guard: it reports ok.
packages/driversis altimate-owned (it does not exist on upstreamdev), so no markers are needed.
Remaining minors. None of them blocks; each has an inline comment:
- Extra legacy PEM headers are folded into the body: an edge input that no common tool writes.
- An unusable private-key block placed before a valid one: an edge input that needs two keys in one value and a passphrase.
- A key encrypted with an empty passphrase can't be used: an edge input, and it was the same on main.
- EC, Ed25519 and DSA keys get no local "RSA only" message: same as main, and Snowflake rejects them anyway.
PBE-MD5-DESgets the wrong-passphrase wording: a Node/Bun limitation, and the message still mentions an unsupported cipher.- Test coverage gaps: test-only.
The pre-existing key echo in connect() and the nits are in a separate PR comment.
| return " " | ||
| }) | ||
|
|
||
| const body = inner.replace(/\s+/g, "") |
There was a problem hiding this comment.
Minor (edge input, not blocking): extra legacy PEM headers end up in the base64 body. Only Proc-Type and DEK-Info are taken out before whitespace is stripped. Any other RFC 1421 header line before the blank line (for example Comment: hello) gets folded into the body, so decryption fails. Repro: an AES-256-CBC legacy PKCS#1 key with \nComment: hello inserted after DEK-Info, with the correct passphrase. Main decrypts it and returns the matching key; head throws "failed to decrypt the private key". openssl, ssh-keygen and the Snowflake docs commands never write such a header, so this is an edge case. A safe follow-up is to drop any Name: value line in the header area, not just these two.
|
|
||
| // A pasted file may hold other blocks (certificates, public key) before the | ||
| // private key; use the first block that is a private key. | ||
| const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) |
There was a problem hiding this comment.
Minor (edge input, not blocking): the first *PRIVATE KEY block wins even when it can't be used. If an unusable private-key block (for example -----BEGIN OPENSSH PRIVATE KEY-----) comes before a valid PKCS#8 key in the same value and a passphrase is set, main's parser skipped it and connected. Head picks the OpenSSH block and throws "could not be parsed". Without a passphrase, main also failed (the SDK only accepts text starting with -----BEGIN PRIVATE KEY-----), so only the passphrase-set case regresses. This needs two private keys pasted into one value, which is an edge case. A possible follow-up: try each private-key block in turn and keep the first one that parses.
| "('-----BEGIN PRIVATE KEY-----', '-----BEGIN ENCRYPTED PRIVATE KEY-----' or '-----BEGIN RSA PRIVATE KEY-----').", | ||
| ) | ||
| } | ||
| const pass = passphrase && passphrase.length > 0 ? passphrase : undefined |
There was a problem hiding this comment.
Minor (edge input, pre-existing, not blocking): a key encrypted with an empty passphrase can't be used. passphrase: "" is treated as no passphrase, so a key encrypted with "" gets "key is encrypted; set the passphrase". crypto.createPrivateKey({ key, passphrase: "" }) would decrypt it. Main fails this case too. It is very rare.
| } | ||
|
|
||
| try { | ||
| const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) |
There was a problem hiding this comment.
Minor (not blocking, same as main): EC (SEC1 and PKCS#8), Ed25519 and DSA keys pass here with no local message. They are converted to PKCS#8 and handed to the SDK. snowflake-sdk 2.x then signs the JWT with RS256 through jsonwebtoken, which rejects a non-RSA key, so the user never sees this module's "use an RSA key" hint. Snowflake accepts only RSA keys. A short keyObject.asymmetricKeyType !== "rsa" check with a fixed message would make this clear. I understand the reply that rejecting key types is out of scope; this is a follow-up, not a block.
| const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) | ||
| return keyObject.export({ type: "pkcs8", format: "pem" }).toString() | ||
| } catch { | ||
| if (encrypted) { |
There was a problem hiding this comment.
Minor (Node/Bun limitation, not blocking): an unsupported encryption scheme gets the wrong-passphrase message. PKCS#8 encrypted with PBES1 PBE-MD5-DES (openssl pkcs8 -topk8 -v1 PBE-MD5-DES) cannot be decoded by Bun (BoringSSL) or Node 26 (OpenSSL 3.5, legacy provider off). The user gets "The passphrase ... is incorrect, or the key is corrupted or uses an unsupported cipher" even when the passphrase is right. The message does mention an unsupported cipher, but it does not name the scheme. Under Bun, these all decode correctly: PBES2 AES-256/AES-128/DES-EDE3, PBES1 PBE-SHA1-3DES, and legacy AES-128-CBC/AES-256-CBC/DES-EDE3-CBC. A follow-up could suggest re-encrypting with openssl pkcs8 -topk8 -v2 aes-256-cbc.
|
|
||
| const pkcs8 = rsa.privateKey.export({ type: "pkcs8", format: "pem" }) as string | ||
| const pkcs1 = rsa.privateKey.export({ type: "pkcs1", format: "pem" }) as string | ||
| const pkcs8Enc = rsa.privateKey.export({ type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase: PASS }) as string |
There was a problem hiding this comment.
Minor (test-only, not blocking): the fixtures cover one 2048-bit RSA key and one cipher. No test covers: extra legacy headers, an unusable private-key block before a valid one, 1024/4096-bit keys, other ciphers, or connect() with inline text that has no -----BEGIN. Mutation results: removing the quote-strip loop, or keeping spaces inside the body (removing only newlines), passes all 36 tests. Both are redundant in practice (details in the PR comment). Removing the Proc-Type/DEK-Info handling fails 6-8 tests, removing the literal-escape conversion fails 7, and taking the first PEM block of any kind fails 1.
|
Consensus review follow-ups (Claude + Codex): items not tied to a diff line, plus nits Pre-existing, outside this diff. Worth a follow-up, not a block for this PR: Nits
|
Issue for this PR
Closes #
Type of change
What does this PR do?
The local Snowflake driver's key-pair handling only decrypted keys when a passphrase was set or the text contained "ENCRYPTED", and only normalized literal
\n. PEMs whose line breaks became spaces, encrypted PKCS#8 keys without a passphrase, and legacy encrypted PKCS#1 keys (Proc-Type/DEK-Info) failed with raw OpenSSL errors such as1E08010C:DECODER routines::unsupported.The key handling now lives in
packages/drivers/src/snowflake-key.ts: it strips surrounding quotes, converts literal\n, CRLF and space-separated bodies back to 64-char lines between the BEGIN/END markers (keeping legacy headers on their own lines), then converts any supported key (unencrypted PKCS#1/PKCS#8, encrypted PKCS#8, legacy-encrypted PKCS#1) to unencrypted PKCS#8 for the SDK. A missing passphrase gives "key is encrypted; set the passphrase", a wrong passphrase or unparseable key gives a fixed message; no key material or OpenSSL text is included.How did you verify your code works?
New
packages/drivers/test/snowflake-key.test.tsgenerates keys at test time withnode:cryptofor each format and variant (multiline, CRLF, space-separated,\n-escaped, quoted), plus error cases andconnect()wiring. Theconnect()tests fail on origin/main.bun typecheckand the snowflake driver tests pass.Cost side effects
None.
Screenshots / recordings
N/A
Checklist
Summary by cubic
Makes the Snowflake driver accept every common private-key format, so key-pair auth no longer fails on formatting quirks like escaped newlines, quotes, CRLF, or space-separated bodies.
\nsequences, space-joined bodies, CRLF) back to canonical 64-char-line form.snowflake-sdk.private_key_passphrasenow raises a clear, actionable error without echoing key material or OpenSSL internals.snowflake-key.tswith a test suite covering every format and variant.Written for commit 7c5c792. Summary will update on new commits.
Summary by CodeRabbit